package com.example.secondhandspringboot.websocket;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.secondhandspringboot.domain.entity.ChatMessages;
import com.example.secondhandspringboot.domain.entity.Contacts;
import com.example.secondhandspringboot.exception.BaseException;
import com.example.secondhandspringboot.mapper.ContactsMapper;
import com.example.secondhandspringboot.service.IContactsService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.OnMessage;
import javax.websocket.OnError;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
@ServerEndpoint(value = "/websocket/{userId}")
public class WebSocketServer {

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    /**
     * 用户ID
     */
    private Long userId;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    //虽然@Component默认是单例模式的，但springboot还是会为每个websocket连接初始化一个bean，所以可以用一个静态set保存起来。
    //  注：底下WebSocket是当前类名
    public static CopyOnWriteArraySet<WebSocketServer> webSockets =new CopyOnWriteArraySet<>();
    // 用来存在线连接用户信息
    public static ConcurrentHashMap<Long,Session> sessionPool = new ConcurrentHashMap<Long,Session>();

    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId") Long userId) {
        if (userId==null){
            throw new BaseException("未登录，请先登录");
        }
        try {
            this.session = session;
            this.userId = userId;
            if (sessionPool.containsKey(userId)){
                return;
            }
            webSockets.add(this);
            sessionPool.put(userId, session);
            log.info("【websocket消息】有新的连接,用户id:"+userId+"，当前在线总数为:"+webSockets.size());
        } catch (Exception e) {
            log.info("websocket连接发生错误:"+e.getMessage());
        }
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            sessionPool.remove(this.userId);
            log.info("【websocket消息】连接断开，当前在线总数为:"+webSockets.size());
        } catch (Exception e) {
            log.info("websocket断开发生错误:"+e.getMessage());
        }
    }
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("【websocket消息】收到客户端消息:"+message);
        //转为对象
        ChatMessages chatMessages = JSON.parseObject(message, ChatMessages.class);
        //获取接收者
        Long receiveUser = chatMessages.getReceiveUser();
        Session session = sessionPool.get(receiveUser);
        if (session!=null&&session.isOpen()) {
            //接收者在线
            session.getAsyncRemote().sendText(chatMessages.getMessageContent());
        }
        chatMessages.setIsRead(0); //未读
        chatMessages.setCreateTime(LocalDateTime.now());
        Db.save(chatMessages);

        //如果接收者还没有发送者联系人，则创建
        Contacts contact = Db.lambdaQuery(Contacts.class).eq(Contacts::getContactUserId, chatMessages.getSendUser())
                .eq(Contacts::getUserId, chatMessages.getReceiveUser()).one();
        if (contact == null){
            Contacts contact1 = new Contacts();
            contact1.setContactUserId(chatMessages.getSendUser());
            contact1.setUserId(chatMessages.getReceiveUser());
            contact1.setCreateTime(LocalDateTime.now());
            Db.save(contact1);
        }
    }

    /** 发送错误时的处理
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        log.error("用户错误,原因:"+error.getMessage());
        error.printStackTrace();
    }


    // 此为广播消息
    public void sendAllMessage(String message) {
        log.info("【websocket消息】广播消息:"+message);
        for(WebSocketServer webSocket : webSockets) {
            try {
                if(webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(Long userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null&&session.isOpen()) {
            try {
                log.info("【websocket消息】 单点消息:"+message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息(多人)
    public void sendMoreMessage(String[] userIds, String message) {
        for(String userId:userIds) {
            Session session = sessionPool.get(userId);
            if (session != null&&session.isOpen()) {
                try {
                    log.info("【websocket消息】 单点消息:"+message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
